<script setup lang="ts">
import _ from 'lodash';
import { ref, watch } from 'vue';

import addIcon from '@/assets/images/add-btn.png';
import delIcon from '@/assets/images/del-icon.png';

const props = defineProps({
  modelValue: {
    type: Array as any,
    default: () => {
      return [];
    },
  },
});

const emits = defineEmits(['update:modelValue', 'change']);

interface valueItem {
  value: string;
}

const initListItem: valueItem = { value: '' };
const valueList = ref<valueItem[]>([{ ...initListItem }]);

const emitData = () => {
  const data = valueList.value.map((item: valueItem) => item.value);
  emits('update:modelValue', data);

  return data;
};

// 删
const handleDelIcon = (num: any) => {
  valueList.value = valueList.value.filter((item: valueItem, index: number) => index !== num);
  emitData();
};

// 增
const handleAddItem = () => {
  valueList.value.push({ ...initListItem });
  emitData();
};

// 值变化
const handleChange = () => {
  const data = emitData();
  emits('change', data);
};

// 过滤空值
const filterBlankData = (list: string[]) => {
  return list.filter((item: string) => item);
};

watch(
  () => props.modelValue,
  (list) => {
    const dataList = list.map((item: any) => {
      const data = _.cloneDeep(initListItem);
      data.value = item;
      return data;
    });
    valueList.value = _.cloneDeep(dataList);
  },
  { immediate: true },
);

defineExpose({ filterBlankData });
</script>

<template>
  <div class="input-edit">
    <div class="list">
      <div v-for="(item, index) in valueList" :key="index" class="input-item">
        <t-input v-model="item.value" class="inputs" @change="handleChange"></t-input>
        <img
          v-if="valueList.length > 1 || index !== 0"
          class="del-icon"
          :src="delIcon"
          alt=""
          @click="handleDelIcon(index)"
        />
      </div>
      <img class="add-icon" :src="addIcon" alt="" @click="handleAddItem" />
    </div>
  </div>
</template>

<style scoped lang="less">
.input-edit {
  box-sizing: border-box;
  width: 100%;

  .list {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    margin-left: -16px;

    .input-item {
      width: 380px;
      position: relative;
      margin-left: 16px;
      margin-bottom: 16px;

      .del-icon {
        width: 16px;
        height: 16px;
        position: absolute;
        right: -8px;
        top: -8px;
        z-index: 999;
        cursor: pointer;

        &:hover {
          opacity: 0.9;
        }
      }
    }

    .add-icon {
      width: 32px;
      height: 32px;
      margin-left: 16px;
      cursor: pointer;

      &:hover {
        opacity: 0.9;
      }
    }
  }
}
</style>
